/**
 * 
 */
package me.whily.nutzbook.shiro.realm;

import me.whily.nutzbook.bean.User;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.integration.shiro.CaptchaUsernamePasswordToken;
import org.nutz.ioc.loader.annotation.Inject;


/**
 * @author Administrator
 * @since 2015年8月14日 下午4:34:07
 *
 */
public class NutDaoRealm extends AuthenticatingRealm {

	@Inject
	protected Dao dao;
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		CaptchaUsernamePasswordToken upToken = (CaptchaUsernamePasswordToken)token;
		
		User user = dao.fetch(User.class, Cnd.where("name", "=", upToken.getUsername()));
		if (user == null)
			return null;
		if (user.isLocked())
			throw new LockedAccountException("Account [" + upToken.getUsername() + "] is locked.");
		
		SimpleAccount account = new SimpleAccount(user.getId(), user.getPassword(), getName());
		account.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
		
		return account;
	}
	
	
}
